<?php
require_once 'includes/constants.php';
session_start();

class Profile {
    
    function __construct(){

            mysql_connect(HOST, DB_USER, DB_PASSWORD) or die("There was a problem with connecting to the database");
            mysql_select_db(DB_NAME) or die("There was a problem with connecting to the database");

    }

    function getRatings($url){

            $query = 'SELECT * from `Ratings` where `Url` = ' . "'" . $url . "'";
            $result = mysql_query($query);
            return mysql_fetch_array($result);

    }

    function rate($url, $rating){
        $current_rating = $this->getRatings($url);
        if(empty($current_rating)){
            $query = "INSERT into `Ratings` (`Url`, `Rating`, `NumberRated`) values('$url', $rating, '1') ";
            $result = mysql_query($query);
        }
        else{
            $new_rating = ($current_rating['Rating'] * $current_rating['NumberRated'] + $rating) / ($current_rating['NumberRated'] + 1) ;

            $query = "UPDATE `Ratings` SET `Rating` = $new_rating, NumberRated=NumberRated+1 WHERE `Url` = '$url'";
            $result = mysql_query($query);
        }

    }



    function gift($url){
        $current_rating = $this->getRatings($url);
        if(empty($current_rating)){
            $query = "INSERT into `Ratings` (`Url`, `NumberGifted`) values('$url', '1') ";
            $result = mysql_query($query);
        }
        else{
            $query = "UPDATE `Ratings` SET NumberGifted=NumberGifted+1 WHERE `Url` = '$url'";
            $result = mysql_query($query);
        }

    }


}


?>
